package myauctioneer;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletRequest;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

public class Customer
{
	protected int id;
	protected String name;
	protected String address;
	protected String phone;
	protected String email;
	protected String password;

	protected App app;

	public Customer(App app)
	{
		this.app = app;
	}

	public int getId()			{ return this.id; }
	public String getName()		{ return this.name; }
	public String getAddress()	{ return this.address; }
	public String getPhone()	{ return this.phone; }
	public String getEmail()	{ return this.email; }
	public String getPassword()	{ return this.password; }

	public void setName(int v)	{ this.id = v; }
	public void setName(String v)	{ this.name = v; }
	public void setAddress(String v)	{ this.address = v; }
	public void setPhone(String v)	{ this.phone = v; }
	public void setEmail(String v)	{ this.email = v; }
	public void setPassword(String v)	{ this.password = v; }
	
	/**
	 * Register new user from UserServlet(...).registerAction(...)
	 */
	public Customer register(HttpServletRequest request)
		throws javax.servlet.ServletException
	{
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {		
			ps = app.getDb().prepareStatement(
				"INSERT INTO customer (NAME,ADDRESS,PHONE,EMAIL,PASSWORD) VALUES(?,?,?,?,?)"
			);
			
			this.setName(request.getParameter("name"));
			ps.setString(1, this.name);
			
			this.setAddress(request.getParameter("address"));
			ps.setString(2, this.address);
			
			this.setPhone(request.getParameter("phone"));
			ps.setString(3, this.phone);
			
			this.setEmail(request.getParameter("email"));
			ps.setString(4, this.email);
			
			this.setPassword(request.getParameter("password"));
			ps.setString(5, this.password);
			
			rs = ps.executeQuery();
			
			//rs.next();
			if (rs == null) throw new javax.servlet.ServletException("Couldn't create new customer in db.");
		}
		catch(SQLException sqle /*Throwable e*/) {
			// ignore
			throw new javax.servlet.ServletException(sqle.toString());
		}
		finally {
			if(ps != null) try { ps.close(); } catch(Throwable e) { }
			if(rs != null) try { rs.close(); } catch(Throwable e) { }
		}
		return this;		
	}

	/**
	 * Load user by id
	 */
	public Customer load(int id)
	{
		try {
			return this._loadHelper('i', new Integer(id));
		}
		catch (javax.servlet.ServletException se) {
		}
		return null;
	}

	/**
	 * Load user by email
	 */
	public Customer loadByEmail(String email)
	{
		try {
			return this._loadHelper('e', email);
		}
		catch (javax.servlet.ServletException se) {
		}
		return null;
	}

	/**
	 * Load helper by predefined types
	 */
	private Customer _loadHelper(char type, Object input)
		throws javax.servlet.ServletException
	{
		PreparedStatement ps = null;
		ResultSet rs = null;

		try {
			switch(type) {
			case 'e':
				ps = app.getDb().prepareStatement(
					"SELECT * FROM customer WHERE email = ?");
				ps.setString(1, (String) input);
				break;
			default:
				ps = app.getDb().prepareStatement(
					"SELECT * FROM customer WHERE customer_id = ?");
				ps.setInt(1, ((Integer)input).intValue());
				//ps.setInt(1, (int) input);
			}

			rs = ps.executeQuery();
			rs.next();

			this.id = rs.getInt("customer_id");
			this.name = rs.getString("name");
			this.email = rs.getString("email");
			this.password = rs.getString("password");
		}
		catch(Exception e /*Throwable e*/) {
			// ignore
			throw new javax.servlet.ServletException(e.toString());
		}
		finally {
			if(ps != null) try { ps.close(); } catch(Throwable e) { }
			if(rs != null) try { rs.close(); } catch(Throwable e) { }
		}

		return this;
	}

	/**
	 * Load user by session, if it where valid.
	 */
	public Customer load(HttpSession session)
	{
		/**
		 * Validation interval for login_time in session.
		 */
		long expreInterval = 24L * 3600L * 1000L; // a day
		//long expreInterval = 20L * 1000L; // 20 sec

		if(session.getAttribute("login_time") != null
			&& session.getAttribute("customer_id") != null)
		{
			long loginTime = ((Long)session.getAttribute("login_time")).longValue();
			int id = ((Integer)session.getAttribute("customer_id")).intValue();

			if(id > 0 && loginTime > System.currentTimeMillis() - expreInterval)
				this.load(id);
		}

		return this;
	}

	/**
	 * Set the user as logged in to the session
	 */
	public Customer setLoggedIn(HttpSession session)
		throws Exception
	{
		if(this.id == 0)
			throw new Exception("Customer data not loaded.");

		session.setAttribute("customer_id", new Integer(this.id));
		session.setAttribute("login_time", new Long(System.currentTimeMillis()));

		return this;
	}
	public boolean isLoggedIn(HttpSession session)
		throws Exception
	{
		try {
			if (this.id > 0 && ((Integer)session.getAttribute("customer_id")).intValue() == this.id)
//			if (this.id > 0 && Integer.parseInt((String)session.getAttribute("customer_id")) == this.id)
			return true;
		}
		catch (NumberFormatException nfe) {
			throw new Exception("Couldn't validate session-values.");
		}
		return false;
	}
}
